<template>
  <common-list>
    <!-- 头部搜素start -->
    <common-search slot="search" @search="handleQuery" @reset="resetQuery">
      <el-form
          :model="query"
          ref="queryForm"
          @submit.native.prevent
          v-show="showSearch"
          :inline="true"
          label-width="65px"
      >
        <el-form-item label="角色名称">
          <common-input v-model="query.roleName" clearable @enter="handleQuery"/>
        </el-form-item>

        <el-form-item label="状态">
          <el-select v-model="query.status" clearable>
            <el-option label="全部" :value="null"></el-option>
            <el-option label="正常" value="0"></el-option>
            <el-option label="停用" value="1"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="创建时间">
          <el-date-picker
              v-model="query.daterange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
              format="yyyy-MM-dd"
              align="right"
          ></el-date-picker>
        </el-form-item>
      </el-form>
    </common-search>
    <!-- 头部搜素end -->

    <!-- 按钮start -->
    <el-row slot="tools" :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            @click="edit(null)"
            v-hasPermi="['system:role:add']"
        >新增
        </el-button
        >
      </el-col>
    </el-row>
    <!-- 按钮end -->

    <!--列表 start-->
    <common-table
        slot="content"
        v-loading="loading"
        :data="list"
        @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center"/>

      <el-table-column
          label="角色名称"
          align="left"
          prop="roleName"
          show-overflow-tooltip
      />

      <!-- <el-table-column label="显示顺序" align="left" prop="a">
        <template slot-scope="{row}">{{ row.roleSort }}</template>
      </el-table-column> -->

      <el-table-column label="状态" align="center" prop="a">
        <template slot-scope="{ row }">
          <el-tag type="success" v-if="row.status == 0">正常</el-tag>
          <el-tag type="danger" v-if="row.status == 1">停用</el-tag>
        </template>
      </el-table-column>

      <el-table-column
          label="创建时间"
          align="left"
          prop="a"
          show-overflow-tooltip
      >
        <template slot-scope="{ row }">{{ row.createTime }}</template>
      </el-table-column>

      <el-table-column label="操作" align="left" width="185">
        <template slot-scope="{ row }">
          <el-button
            type="text"
            @click="setUsers(row)"
            v-hasPermi="['system:role:bindUser']"
          >人员设置
          </el-button
          >
          <el-button
              type="text"
              @click="edit(row)"
              v-hasPermi="['system:role:edit']"
              v-if="row.roleId !== '1'"
          >编辑
          </el-button
          >
          <el-button
              type="text"
              @click="handleShake(row)"
              v-hasPermi="['system:role:changeStatus']"
              v-if="row.roleId !== '1'"
              :disabled="row.isDisabledForShake"
          >
            <span v-if="row.status == 0">停用</span>
            <span v-if="row.status == 1">启用</span>
          </el-button>
          <el-button
              type="text"
              @click="handleDelete(row)"
              v-hasPermi="['system:role:remove']"
              v-if="row.roleId !== '1'"
          >删除
          </el-button
          >
        </template>
      </el-table-column>
    </common-table>

    <pagination
        slot="pagination"
        v-show="total > 0"
        :total="total"
        :page.sync="query.pageNum"
        :limit.sync="query.pageSize"
        @pagination="getList"
    />

    <editDialog ref="editDialog" @refresh="getList"/>

    <!--    <setUsersDialog ref="setUsersDialog" @refresh="getList"></setUsersDialog>-->

    <template v-if="isShowUser">
      <common-choose-user
          ref="chooseUser"
          type="role"
          @close="close"
      ></common-choose-user>
    </template>
  </common-list>
</template>

<script>
import editDialog from './components/roleAdd'
// import setUsersDialog from './components/userAdd'
import {
  role_list,
  role_status,
  role_delete,
  deleteForCheckForRole
} from '@/api/management/usercenter/user.js'
import { selectUsersByRoles, batchAddUserRole } from '@/api/system/user'
import BaseList from '@/mixins/BaseList'
import CommonChooseUser from '@/components/CommonChooseUser'
import importDialogVue from '../../../alarmCenter/components/importDialog.vue'

export default {
  components: { editDialog, CommonChooseUser },
  mixins: [BaseList],
  props: {},
  data() {
    return {
      key:'roleId',
      filterMenu: '', //菜单筛选
      showSearch: true, // 查询部分显示
      total: 1, // 总条数
      loading: false, // table 加载中
      list: [{ a: 1 }], // 数据列
      selectionIds: '', // 列表选中数据id
      single: true, // 非单个禁用
      multiple: true, // 非多个禁用
      query: {
        pageNum: 1,
        pageSize: 10,
        status: null
      }, // 查询条件
      selectedUsersList: [], //人员设置中已选择人员
      isShowUser: false
    }
  },
  watch: {},
  computed: {},
  methods: {
    /**
     * 选择
     */
    handleSelectionChange(selection) {
      this.selectionIds = selection.map((item) => item.id)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /**
     * 获取列表
     */
    getList() {
      this.loading = true
      let query = { ...this.query }
      role_list(query)
          .then((res) => {
            if (res && res.code === 200) {
              this.list = res.rows.reduce((r, c) => {
                r.push({
                  ...c,
                  isDisabledForShake: false
                })
                return r
              }, [])
              this.total = res.total
            } else {
              this.list = []
              this.total = 0
              this.handleListTips(res)
            }
          })
          .finally(() => (this.loading = false))
    },
    /**
     * 查询
     */
    handleQuery() {
      if (!!this.query.daterange) {
        this.query.beginTime = this.query.daterange[0]
        this.query.endTime = this.query.daterange[1]
      } else {
        this.query.beginTime = ''
        this.query.endTime = ''
      }

      this.query.pageNum = 1
      this.getList()
    },
    /**
     * 重置查询
     */
    resetQuery() {
      this.query = this.$options.data().query
    },
    changeStatus(row) {
      return new Promise((resolve, reject) => {
        let status = row.status == 0 ? 1 : 0
        role_status({ roleId: row.roleId, status: status })
            .then((res) => {
              if (res && res.code === 200) {
                this.$GlobalSuccessMessage('操作成功')
                this.query.pageNum = 1
                resolve(res)
                this.getList()
              } else {
                reject()
                this.$GlobalErrorConfirm('操作失败', res.msg)
              }
            }).catch(() => reject())
      })

      // if (row.status == 0) {
      //   status = 1
      //   this.$GlobalDeleteConfirm('停用后将无法进行人员设置，请确认是否停用').then(() => {
      //     role_status({ roleId: row.roleId, status: status }).then(res => {
      //       if (res && res.code === 200) {
      //         this.$GlobalSuccessMessage('操作成功')
      //         this.query.pageNum = 1
      //         this.getList()
      //       } else {
      //         this.$GlobalErrorConfirm('操作失败', res.msg)
      //       }
      //     }).catch(err => {
      //       this.$GlobalErrorConfirm('操作失败', err.msg)
      //     })
      //   })
      // } else {
      //   status = 0
      //   role_status({ roleId: row.roleId, status: status }).then(res => {
      //     if (res && res.code === 200) {
      //       this.$GlobalSuccessMessage('操作成功')
      //       this.query.pageNum = 1
      //       this.getList()
      //     } else {
      //       this.$GlobalErrorConfirm('操作失败', res.msg)
      //     }
      //   }).catch(err => {
      //     this.$GlobalErrorConfirm('操作失败', err.msg)
      //   })
      // }
    },
    /**
     * 添加/编辑
     */
    edit(row) {
      this.$refs.editDialog.show(row ? { ...row } : {})
    },
    /**
     * 人员设置
     */
    setUsers(row) {
      this.isShowUser = true
      this.roleId = row?.roleId

      this.$nextTick(() => {
        this.$refs.chooseUser.show(row ? { ...row } : {})
      })

      // this.isShowUser = true
      // // this.selectUsersUnBindPermission(row?.permissionId)
      // this.roleId = row?.roleId;
      // this.getSelectedUsers(row?.roleId);
      // this.$refs.chooseUser.show(row ? { ...row } : {});
    },
    close() {
      this.isShowUser = false
    },
    /**
     * 获取已选人员
     */
    getSelectedUsers(id) {
      this.selectedUsersList = []
      selectUsersByRoles([id])
          .then((res) => {
            if (res && res.code === 200) {
              this.selectedUsersList = res.data
            } else {
              this.$GlobalErrorConfirm(
                  '获取已选人员失败',
                  res.msg,
                  '重新加载'
              ).then(() => {
                this.getSelectedUsers(id)
              })
              this.handleListTips(res)
            }
          })
    },

    // —————————————————————— 通用删除方法 ——————————————————————

    /**
     * 删除
     */
    deleteData(row) {
      const ids=row?.roleId
      this.$GlobalDeleteConfirm().then(() => {
        role_delete({ ids })
            .then((res) => {
              if (res && res.code === 200) {
                this.$GlobalSuccessMessage('删除成功')
                this.query.pageNum = 1
                this.getList()
              } else {
                this.$GlobalErrorConfirm('删除失败', res.msg)
              }
            })
      }).catch(()=>{});
    },
    /**
     * 删除前校验
     */
    beforeDeleteForCheck(ids) {
      return new Promise((resolve, reject) => {
        deleteForCheckForRole({ ids: ids }).then(res => {
          if(res && res.code === 200) {
            resolve(res)
          } else {
            reject(res)
          }
        }).catch(err => {
          reject(err)
        })
      })
    }

    // submit(val) {
    //   let params = {
    //     roleId: this.roleId,
    //     userIds: val,
    //   };
    //   batchAddUserRole(params)
    //     .then((res) => {
    //       if (res && res.code === 200) {
    //         this.$GlobalSuccessMessage("新增成功");
    //         this.$refs.chooseUser.cancel();
    //         this.getList();
    //       } else {
    //         this.$GlobalErrorConfirm("新增失败", res.msg).then();
    //       }
    //     })
    //     .catch((err) => {
    //       this.$GlobalErrorConfirm("新增失败", err.msg).then();
    //     })
    //     .finally(() => (this.$refs.chooseUser.loading = false));
    // },
  },
  created() {
    this.getList()
  },
  mounted() {
  }
}
</script>
<style lang="scss" scoped>
.container {
  .list-box {
    clear: both;
    height: auto;
    overflow: hidden;
    padding: 20px;
  }
}
</style>
